package com.examination.exam.utils;

import com.examination.auth.utils.SecurityUtil;
import com.examination.domain.exam.base.BaseEntity;
import com.mongodb.client.model.Updates;
import lombok.SneakyThrows;
import org.bson.conversions.Bson;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MetaDataUtil {
    @SneakyThrows
    public static <T> T create(T t) {
        Method getBaseEntity = t.getClass().getMethod("getBaseEntity");
        BaseEntity baseEntity = (BaseEntity) getBaseEntity.invoke(t);
        baseEntity.setCreateBy(String.valueOf(SecurityUtil.getUserId()));
        baseEntity.setCreateTime(getTimeStr());
        baseEntity.setIsDelete(0);
        return t;
    }

    public static List<Bson> update() {
        List<Bson> bsons = new ArrayList<>();
        bsons.add(Updates.set("baseEntity.updateBy", String.valueOf(SecurityUtil.getUserId())));
        bsons.add(Updates.set("baseEntity.updateTime", getTimeStr()));
        return bsons;
    }

    public static List<Bson> delete() {
        List<Bson> bsons = new ArrayList<>();
        bsons.add(Updates.set("baseEntity.updateBy", String.valueOf(SecurityUtil.getUserId())));
        bsons.add(Updates.set("baseEntity.updateTime", getTimeStr()));
        bsons.add(Updates.set("baseEntity.isDelete", 1));
        return bsons;
    }

    public static String getTimeStr() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String dateStr = formatter.format(date);
        return dateStr;
    }

}
